<template>
  <div class="app-container">
    <!-- 顶部统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <i class="el-icon-data-line"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalChapters }}</div>
              <div class="stat-label">总章节数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon completed">
              <i class="el-icon-check"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.completedChapters }}</div>
              <div class="stat-label">已完成</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon time">
              <i class="el-icon-time"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalStudyTime }}</div>
              <div class="stat-label">总学习时长(小时)</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon progress">
              <i class="el-icon-pie-chart"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.overallProgress }}%</div>
              <div class="stat-label">整体进度</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 学习进度概览 -->
    <div class="progress-overview">
      <el-row :gutter="20">
        <el-col :span="16">
          <div class="overview-card">
            <h3 class="overview-title">
              <i class="el-icon-data-line"></i> 章节学习进度
            </h3>
            <div class="chapter-progress">
              <div v-for="chapter in recentChapters" :key="chapter.chapterId" class="chapter-item">
                <div class="chapter-header">
                  <span class="chapter-name">{{ chapter.chapterName || `第${chapter.chapterId}章` }}</span>
                  <span class="chapter-progress-text">{{ chapter.progress }}%</span>
                </div>
                <el-progress 
                  :percentage="chapter.progress || 0" 
                  :stroke-width="8"
                  :show-text="false"
                  :color="getProgressColor(chapter.progress)"
                ></el-progress>
                <div class="chapter-info">
                  <span class="study-time">{{ chapter.studyTime || 0 }}分钟</span>
                  <span class="last-access">{{ formatLastAccess(chapter.lastAccessTime) }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="overview-card">
            <h3 class="overview-title">
              <i class="el-icon-time"></i> 学习时间统计
            </h3>
            <div class="time-stats">
              <div class="time-item">
                <span class="time-label">本周学习</span>
                <span class="time-value">{{ timeStats.weeklyStudy }}小时</span>
              </div>
              <div class="time-item">
                <span class="time-label">本月学习</span>
                <span class="time-value">{{ timeStats.monthlyStudy }}小时</span>
              </div>
              <div class="time-item">
                <span class="time-label">连续天数</span>
                <span class="time-value">{{ timeStats.streakDays }}天</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 查询表单区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px" class="search-form">
      <el-row :gutter="20">
        <el-col :span="6">
      <el-form-item label="学生ID" prop="studentId">
        <el-input
          v-model="queryParams.studentId"
          placeholder="请输入学生ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        </el-col>
        <el-col :span="6">
      <el-form-item label="开课ID" prop="offeringId">
        <el-input
          v-model="queryParams.offeringId"
          placeholder="请输入开课ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="完成状态" prop="completionStatus">
            <el-select v-model="queryParams.completionStatus" placeholder="请选择状态" clearable>
              <el-option label="已完成" value="completed"></el-option>
              <el-option label="进行中" value="in_progress"></el-option>
              <el-option label="未开始" value="not_started"></el-option>
            </el-select>
      </el-form-item>
        </el-col>
        <el-col :span="6">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:learningProgress:add']"
        >新增进度</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:learningProgress:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:learningProgress:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:learningProgress:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="learningProgressList" @selection-change="handleSelectionChange" class="learning-progress-table">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="进度ID" align="center" prop="progrId" width="80" />
      <el-table-column label="学生ID" align="center" prop="studentId" width="80" />
      <el-table-column label="开课ID" align="center" prop="offeringId" width="80" />
      <el-table-column label="章节信息" align="center" min-width="150">
        <template slot-scope="scope">
          <div class="chapter-info-cell">
            <span class="chapter-name">{{ scope.row.chapterName || `第${scope.row.chapterId}章` }}</span>
            <el-tag 
              v-if="scope.row.experimentId" 
              type="success" 
              size="mini"
            >实验{{ scope.row.experimentId }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="完成状态" align="center" prop="completionStatus" width="100">
        <template slot-scope="scope">
          <el-tag :type="getCompletionStatusType(scope.row.completionStatus)" size="mini">
            {{ getCompletionStatusText(scope.row.completionStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="学习时长" align="center" prop="learningDuration" width="100">
        <template slot-scope="scope">
          <span class="duration-display">{{ scope.row.learningDuration || 0 }}分钟</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="completionTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.completionTime, '{m}-{d}') || '未完成' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后访问" align="center" prop="lastAccessTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastAccessTime, '{m}-{d}') || '未访问' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
                      <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:learningProgress:edit']"
            >修改</el-button>
                      <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:learningProgress:remove']"
            >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增或修改学习进度对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
        <el-form-item label="学生ID" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学生ID" />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="开课ID" prop="offeringId">
          <el-input v-model="form.offeringId" placeholder="请输入开课ID" />
        </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
        <el-form-item label="章节ID" prop="chapterId">
          <el-input v-model="form.chapterId" placeholder="请输入章节ID" />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="实验ID" prop="experimentId">
          <el-input v-model="form.experimentId" placeholder="请输入实验ID" />
        </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="完成状态" prop="completionStatus">
              <el-select v-model="form.completionStatus" placeholder="请选择完成状态" style="width: 100%">
                <el-option label="已完成" value="completed"></el-option>
                <el-option label="进行中" value="in_progress"></el-option>
                <el-option label="未开始" value="not_started"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学习时长(分钟)" prop="learningDuration">
              <el-input-number 
                v-model="form.learningDuration" 
                :min="0" 
                :max="1440"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
        <el-form-item label="完成时间" prop="completionTime">
              <el-date-picker
            v-model="form.completionTime"
                type="datetime"
                placeholder="请选择完成时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="最后访问时间" prop="lastAccessTime">
              <el-date-picker
            v-model="form.lastAccessTime"
                type="datetime"
                placeholder="请选择最后访问时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              />
        </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLearningProgress, getLearningProgress, delLearningProgress, addLearningProgress, updateLearningProgress } from "@/api/system/learningProgress"

export default {
  name: "LearningProgress",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学习进度表格数据
      learningProgressList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentId: null,
        offeringId: null,
        completionStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        studentId: [
          { required: true, message: "学生ID不能为空", trigger: "blur" }
        ],
        offeringId: [
          { required: true, message: "开课ID不能为空", trigger: "blur" }
        ],
        chapterId: [
          { required: true, message: "章节ID不能为空", trigger: "blur" }
        ]
      },
      // 统计数据
      stats: {
        totalChapters: 24,
        completedChapters: 18,
        totalStudyTime: 156,
        overallProgress: 75
      },
      // 时间统计
      timeStats: {
        weeklyStudy: 12,
        monthlyStudy: 48,
        streakDays: 7
      },
      // 最近章节
      recentChapters: [
        {
          chapterId: 1,
          chapterName: '数据结构基础',
          progress: 85,
          studyTime: 120,
          lastAccessTime: '2025-01-20 10:30:00'
        },
        {
          chapterId: 2,
          chapterName: '算法设计',
          progress: 60,
          studyTime: 90,
          lastAccessTime: '2025-01-19 15:20:00'
        },
        {
          chapterId: 3,
          chapterName: '排序算法',
          progress: 100,
          studyTime: 180,
          lastAccessTime: '2025-01-18 09:15:00'
        }
      ]
    }
  },
  created() {
    this.getList()
    this.getStats()
  },
  methods: {
    /** 查询学习进度列表 */
    getList() {
      this.loading = true
      listLearningProgress(this.queryParams).then(response => {
        this.learningProgressList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取统计数据 */
    getStats() {
      // 这里可以调用统计接口，暂时使用模拟数据
      this.stats = {
        totalChapters: 24,
        completedChapters: 18,
        totalStudyTime: 156,
        overallProgress: 75
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        progrId: null,
        studentId: null,
        offeringId: null,
        chapterId: null,
        experimentId: null,
        completionStatus: 'not_started',
        learningDuration: 0,
        completionTime: null,
        lastAccessTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.progrId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "新增学习进度"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const progrId = row.progrId || this.ids
      getLearningProgress(progrId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改学习进度"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.progrId != null) {
            updateLearningProgress(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addLearningProgress(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const progrIds = row.progrId || this.ids
      this.$modal.confirm('是否确认删除学习进度编号为"' + progrIds + '"的数据项？').then(function() {
        return delLearningProgress(progrIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/learningProgress/export', {
        ...this.queryParams
      }, `learningProgress_${new Date().getTime()}.xlsx`)
    },
    /** 获取完成状态类型 */
    getCompletionStatusType(status) {
      const typeMap = {
        'completed': 'success',
        'in_progress': 'warning',
        'not_started': 'info'
      }
      return typeMap[status] || 'info'
    },
    /** 获取完成状态文本 */
    getCompletionStatusText(status) {
      const textMap = {
        'completed': '已完成',
        'in_progress': '进行中',
        'not_started': '未开始'
      }
      return textMap[status] || '未知'
    },
    /** 获取进度颜色 */
    getProgressColor(progress) {
      if (progress >= 80) return '#67c23a'
      if (progress >= 60) return '#409eff'
      if (progress >= 40) return '#e6a23c'
      return '#f56c6c'
    },
    /** 格式化最后访问时间 */
    formatLastAccess(time) {
      if (!time) return '未访问'
      const lastAccess = new Date(time)
      const now = new Date()
      const diffHours = (now - lastAccess) / (1000 * 60 * 60)
      if (diffHours < 24) return `${Math.floor(diffHours)}小时前`
      if (diffHours < 168) return `${Math.floor(diffHours / 24)}天前`
      return parseTime(time, '{m}-{d}')
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.stat-icon.completed {
  background: #67c23a;
}

.stat-icon.time {
  background: #e6a23c;
}

.stat-icon.progress {
  background: #f56c6c;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.progress-overview {
  margin-bottom: 20px;
}

.overview-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  height: 100%;
}

.overview-title {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.chapter-progress {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.chapter-item {
  .chapter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }
  
  .chapter-name {
    font-size: 14px;
    color: #303133;
    font-weight: 500;
  }
  
  .chapter-progress-text {
    font-size: 12px;
    color: #409eff;
    font-weight: 600;
  }
  
  .chapter-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 8px;
    font-size: 12px;
    color: #909399;
  }
}

.time-stats {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.time-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.time-label {
  font-size: 14px;
  color: #606266;
}

.time-value {
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

.search-form {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.learning-progress-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.chapter-info-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chapter-name {
  font-weight: 600;
  color: #303133;
}

.duration-display {
  font-weight: 600;
  color: #409eff;
}

@media (max-width: 768px) {
  .stats-cards .el-col {
    margin-bottom: 16px;
  }
  
  .progress-overview .el-col {
    margin-bottom: 16px;
  }
  
  .search-form .el-col {
    margin-bottom: 16px;
  }
}
</style>
